package com.user.handler;

import com.common.exception.users.LoginException;
import com.user.domain.pojo.User;
import com.user.service.IUserService;
import com.user.service.impl.UserDetailsServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("username-password-login")
public class UsernamePasswordHandler implements LoginHandler{

    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Resource
    IUserService iUserService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails login(Object principal, Object credentials) throws AuthenticationException {
        String username = (String) principal;
        String password = (String) credentials;
        User user = iUserService.querySelectByUniqueIdentification(username);
        if (user == null){
            throw new UsernameNotFoundException(LoginException.USERS_NULL);
        }
        if (!passwordEncoder.matches(password, user.getPassword())){
            throw new BadCredentialsException(LoginException.USERNAME_PASSWORD_ERROR);
        }
        return userDetailsService.loadUserByUsername((String) principal);
    }
}
